package com.exampletest.controller;

import com.exampletest.model.Enterprise;
import com.exampletest.model.User;
import com.exampletest.service.EnterpriseService;
import com.exampletest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private HttpSession session;


    @GetMapping("/login")
    public String loginPage() {
        return "user/login";
    }

    // 在原有代码基础上修改login方法
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password,
                        Model model, HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            System.out.println("登录用户: " + user.getUsername() +
                    ", isSuperAdmin: " + user.getIsSuperAdmin()); // 调试输出
            session.setAttribute("user", user);
            if (user.getIsSuperAdmin() != null && user.getIsSuperAdmin()) {
                System.out.println("重定向到/admin/dashboard"); // 调试输出
                return "redirect:/admin/dashboard";
            } else {
                System.out.println("重定向到/index"); // 调试输出
                return "redirect:/index";
            }
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "user/login";
        }
    }

    // 添加dashboard方法
    @GetMapping("/index")
    public String userDashboard(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        return "index";
    }

    @GetMapping("/register")
    public String registerPage(Model model) {
        // 从数据库获取企业列表
        List<Enterprise> enterprises = enterpriseService.getAllEnterprises();

        // 将企业列表添加到模型中
        model.addAttribute("enterprises", enterprises);

        return "user/register";
    }

    @PostMapping("/register")
    public String register(
            @RequestParam String account,
            @RequestParam String password,
            @RequestParam String confirmPassword,
            @RequestParam String nickname,
            @RequestParam String gender,
            @RequestParam String phoneNumber,
            @RequestParam String email,
            @RequestParam Integer enterpriseId,
            Model model) {

        // 验证密码是否匹配
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "user/register";
        }

        // 创建用户对象并设置所有属性
        User user = new User();
        user.setUsername(account);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setGender(gender);
        user.setPhoneNumber(phoneNumber);
        user.setEmail(email);
        user.setEnterpriseId(enterpriseId);
        user.setCreateTime(new Date());
        user.setStatus(1); // 激活状态

        boolean success = userService.register(user);
        if (success) {
            return "redirect:/user/login";
        } else {
            model.addAttribute("error", "用户名已存在");
            return "user/register";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/user/login";
    }


    // 用户管理
    @GetMapping("/list")
    public String listUsers(@RequestParam(required = false) String keyword, Model model) {
        List<User> users;
        if (keyword != null && !keyword.isEmpty()) {
            users = userService.searchUsers(keyword);
        } else {
            users = userService.getAllUsers();
        }

        // 获取所有企业并转换为Map
        List<Enterprise> enterprises = enterpriseService.getAllEnterprises();
        Map<Integer, Enterprise> enterpriseMap = enterprises.stream()
                .collect(Collectors.toMap(Enterprise::getId, Function.identity()));

        model.addAttribute("users", users);
        model.addAttribute("keyword", keyword);
        model.addAttribute("enterpriseMap", enterpriseMap);
        return "user/list";
    }

    @GetMapping("/add")
    public String addUserPage() {
        return "user/add";
    }

//    @PostMapping("/add")
//    public String addUser(User user, Model model) {
//        boolean success = userService.register(user.getUsername(), user.getPassword());
//        if (success) {
//            return "redirect:/user/list";
//        } else {
//            model.addAttribute("error", "用户名已存在");
//            return "user/add";
//        }
//    }

    @GetMapping("/edit/{id}")
    public String editUserPage(@PathVariable Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @PostMapping("/update")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return "redirect:/user/list";
    }

    @GetMapping("/status/{id}/{status}")
    public String changeUserStatus(@PathVariable Integer id, @PathVariable Integer status) {
        userService.changeUserStatus(id, status);
        return "redirect:/user/list";
    }
    @GetMapping("/user/create")
    public String showCreateUserForm(Model model) {
        // 从数据库获取企业列表
        List<Enterprise> enterprises = enterpriseService.getAllEnterprises();

        // 将企业列表添加到模型中
        model.addAttribute("enterprises", enterprises);

        // 返回视图名称
        return "user/login";
    }

    @GetMapping("/profile")
    public String profilePage(HttpSession session, Model model) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }

        // 获取企业信息
        User user = (User) session.getAttribute("user");
        if (user.getEnterpriseId() != null) {
            Enterprise enterprise = enterpriseService.getEnterpriseById(user.getEnterpriseId());
            model.addAttribute("enterprise", enterprise);
        }

        // 获取所有企业并转换为Map
        List<Enterprise> enterprises = enterpriseService.getAllEnterprises();
        Map<Integer, Enterprise> enterpriseMap = enterprises.stream()
                .collect(Collectors.toMap(Enterprise::getId, Function.identity()));

        model.addAttribute("enterpriseMap", enterpriseMap);
        return "user/profile";
    }


    @PostMapping("/profile/update")
    public String updateProfile(@ModelAttribute User updatedUser,
                                @RequestParam(required = false) String currentPassword,
                                @RequestParam(required = false) String newPassword,
                                @RequestParam(required = false) String confirmPassword,
                                HttpSession session,
                                Model model) {
        User currentUser = (User) session.getAttribute("user");

        // 更新基本信息
        currentUser.setNickname(updatedUser.getNickname());
        currentUser.setGender(updatedUser.getGender());
        currentUser.setPhoneNumber(updatedUser.getPhoneNumber());
        currentUser.setEmail(updatedUser.getEmail());

        // 处理密码修改
        if (StringUtils.hasText(currentPassword) &&
                StringUtils.hasText(newPassword) &&
                StringUtils.hasText(confirmPassword)) {

            // 验证当前密码
            if (userService.login(currentUser.getUsername(), currentPassword)==null) {
                model.addAttribute("error", "当前密码不正确");
                return "user/profile";
            }

            // 验证新密码是否一致
            if (!newPassword.equals(confirmPassword)) {
                model.addAttribute("error", "两次输入的新密码不一致");
                return "user/profile";
            }

            // 更新密码
            currentUser.setPassword(newPassword);
        }

        // 保存更新
        userService.updateUser(currentUser);
        session.setAttribute("user", currentUser);

        model.addAttribute("success", "个人资料更新成功");
        return "user/profile";
    }

} 